import React, { useRef, useMemo, useState } from 'react';
import { connect, history, request } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { AnnounceManageAPI } from '../common/type';
import { SchemaManage } from '@/components/SchemaComponent';
import {
  getAnnounceManageTabSwitch,
  getAnnounceManageTableColumns,
} from '../mconfig';
import { AnnounceManageService, toTopService } from '../service';
import { getKeyRouter } from '@/utils';
import { AnnounceCheckModal } from './AnnounceCheckModal';
import { AnnounceCancelModal } from './AnnounceCancelModal';
import { message } from 'antd';

/** 公告管理页面 */
const AnnounceManageView: React.FC<AnnounceManageAPI.IManageType> = ({
  permissions,
}) => {
  const schemaManageRef: any = useRef();

  /** 获取管理页面上下文内容 */
  const {
    loading,
    pagination,
    searchList,
    data,
    refreshRequest,
    manageTableParams,
  } = AnnounceManageService(permissions);

  /** 头部Tab切换 */
  const onSwitch = (
    key: string | undefined | number,
    searchValues: any,
    params: any,
  ) => {
    if (key) {
      refreshRequest({ ...params, ...searchValues });
    }
  };

  /**
   * 审核modal
   */
  const [checkModal, setCheckModal] = useState<boolean>(false);

  /**
   * 作废modal
   */
  const [cancelModal, setCancelModal] = useState<boolean>(false);

  /**
   * 保存选中数据
   */
  const [checkRowObj, setCheckRowObj] = useState<any>();

  /** 点击搜索提交按钮 */
  const onSearch = (requestParams: AnnounceManageAPI.ITableRequestType) => {
    refreshRequest(requestParams);
  };

  /** 点击搜索重置按钮 */
  const onReset = (requestParams: any) => {
    refreshRequest(requestParams);
  };

  /** 点击分页操作 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    refreshRequest({ pageSize, current, ...params });
  };

  /** 表格头部切换方法 */
  const switchList: AnnounceManageAPI.IHeaderTabsSwitchType = useMemo(() => {
    const switchArr = getAnnounceManageTabSwitch(permissions);
    return switchArr;
  }, [permissions]);

  /** 管理页面头部操作集合 */
  const getSearchOperateFuncs: AnnounceManageAPI.IHeaderActionType =
    useMemo(() => {
      return [
        {
          title: '添加',
          visible: permissions?.['/announceController/add'] ?? false,
          type: 'primary',
          icon: <PlusOutlined />,
          onClick: () => {
            history.push(
              `/announceController/add/:${getKeyRouter()}${getKeyRouter()}`,
            );
          },
        },
      ];
    }, [permissions]);

  /**
   * 接口回调
   * @param res
   */
  const interfaceCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  const { toTopLoading, toTopRun } = toTopService(interfaceCallback);

  /** 数据表格操作集合 */
  const getTableOperateFuncs: AnnounceManageAPI.ITableActionType = {
    onEdit: (record) => {
      history.push({
        pathname: `/announceController/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: record?.id,
        },
      });
    },
    onView: (resObj) => {
      history.push({
        pathname: `/announceController/getAnnounceByID/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: resObj?.id,
        },
      });
    },
    onCheck: (resObj) => {
      setCheckRowObj(resObj);
      setCheckModal(true);
    },
    onCancel: (resObj) => {
      setCheckRowObj(resObj);
      setCancelModal(true);
    },
    /**置顶 */
    onIsTop: (resObj) => {
      let payload: any = {
        id: resObj?.id,
        isTop: resObj?.isTop == 0 ? 1 : resObj?.isTop == 1 ? 0 : null,
      };
      toTopRun(payload);
    },

    /**审核 */
    goToCheck: (resObj) => {
      history.push({
        pathname: `/announceController/getAnnounceByID/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: resObj?.id,
        },
      });
    },
  };

  /** 获取数据表格数据列 */
  const getTableColumns: Record<string, any>[] = useMemo(() => {
    return getAnnounceManageTableColumns(permissions, getTableOperateFuncs);
  }, [permissions]);

  /**
   * 刷新管理页
   */
  const reloadManage = () => {
    refreshRequest(manageTableParams);
  };

  return (
    <>
      <SchemaManage
        ref={schemaManageRef}
        searchProps={{
          switchList,
          searchList,
          onSwitch,
          onReset,
          onSearch,
        }}
        actionList={getSearchOperateFuncs}
        tableProps={{
          columns: getTableColumns,
          dataSource: data?.rows,
          loading: loading,
          pagination: pagination as any,
          rowKey: 'id',
          onPageChange: onPageChange,
        }}
      />
      {/* 发起审核 */}
      {checkModal && (
        <AnnounceCheckModal
          onClose={() => {
            setCheckModal(false);
          }}
          isShowModal={checkModal}
          checkRows={checkRowObj}
          reloadAnnounce={() => {
            reloadManage();
          }}
        />
      )}

      {/* 作废 */}
      {cancelModal && (
        <AnnounceCancelModal
          onClose={() => {
            setCancelModal(false);
          }}
          isShowModal={cancelModal}
          checkRows={checkRowObj}
          reloadAnnounce={() => {
            reloadManage();
          }}
        />
      )}
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  permissions: baseLogin?.permissions,
  navTab,
}))(AnnounceManageView);
